# coding=utf-8
import os
import shutil

from cal_ops.point import cal_point1
from mylib import download_all
from mylib.mydb import MyDB


def clear_dir(d='result'):
    if os.path.exists(d):
        shutil.rmtree(d)
    os.makedirs(d)


def get_all_stock_csv_path():
    for root, dirs, files in os.walk('stocks'):
        return [os.path.join(root, item) for item in files]


def change_all_stockcsv2sqlite():
    all_stocks_path_list = get_all_stock_csv_path()
    for sp in all_stocks_path_list:
        table_name = sp.replace('.csv', '').replace('stocks/', 'stock_').replace('.', '_')
        mydb.change_csv2sqlite(csv_name=sp, table_name=table_name, from_col=1)


def get_stocks_indus(stocks):
    indus_set = set()
    for stock in stocks:
        indus_set.add(mydb.select_indus_from_db(stock))
    indus = list(indus_set)
    return indus


def get_stocks_from_txt():
    with open('stocks.txt') as fr:
        return [l.strip() for l in fr.readlines() if l]


if __name__ == '__main__':
    mydb = MyDB()

    log_dir = os.path.basename(__file__).split('.')[0]
    clear_dir(log_dir)
    bkd = 100
    start_date = 20241212
    stocks = get_stocks_from_txt()
    download_all.run(stocks[:1])

    indus = get_stocks_indus(stocks[1:])
    # 更新所有上市票
    # update_all_csv.run()
    # 下载所有票最新数据
    download_all.run(stocks)

    # 计算最近40个峰谷点
    cal_point1.run(log_dir, start_date, stocks, indus=indus, bkd=bkd, N=6)
